package com.yumo.kangchenjunga.activity;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Converter;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.springframework.lang.NonNull;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.yumo.kangchenjunga.company.CompanyEntity;

@Entity
@Table(name = "activity")
public class Activity {

	@Column(name = "activity_id", updatable = false)
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private Integer id;
	public String title;
	public String content;
	@OneToOne
	@JoinColumn(name = "company_id")
	public CompanyEntity company;
	public String scope;
	public LocalDate startDate;
	public LocalDate endDate;
	@Convert(converter = CustomerLevelsConverter.class)
	public Set<Integer> customerLevels;
	public Integer quantity;
	public BigDecimal price;
	public String remark;
	@Enumerated(EnumType.STRING)
	public Status status = Status.VALID;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getCustomerLevels() {
		return joinSet(customerLevels);
	}

	public void setCustomerLevels(String customerLevels) {
		this.customerLevels = splitString(customerLevels);
	}

	public static Activity newActivity(ActivityRepository repository, Activity activity) {
		activity.id = 0;

		return repository.save(activity);
	}

	private static String joinSet(Set<Integer> customerLevels) {
		return Joiner.on(',').join(customerLevels);
	}

	private static Set<Integer> splitString(String customerLevels) {
		return new TreeSet<>(Splitter.on(',').omitEmptyStrings().trimResults()
				.splitToList(customerLevels).stream().map(it -> Integer.valueOf(it)).collect(Collectors.toList()));
	}

	@Converter
	public static class CustomerLevelsConverter implements AttributeConverter<Set<Integer>, String> {

		@NonNull
		@Override
		public String convertToDatabaseColumn(Set<Integer> customerLevels) {
			return Activity.joinSet(customerLevels);
		}

		@NonNull
		@Override
		public Set<Integer> convertToEntityAttribute(String customerLevels) {
			return Activity.splitString(customerLevels);
		}
	}

}
